<?php

namespace App\Repositories;

use App\Models\Room;
use Illuminate\Database\Eloquent\Collection;

class RoomRepository extends BaseRepository
{
    public function __construct(Room $model)
    {
        parent::__construct($model);
    }

    /**
     * 根据room_id查找房间
     */
    public function findByRoomId(string $roomId): ?Room
    {
        return $this->model->where('room_id', $roomId)->first();
    }

    /**
     * 获取用户创建的房间
     */
    public function getCreatedByUser(int $userId): Collection
    {
        return $this->model->where('creator_id', $userId)->get();
    }

    /**
     * 获取活跃房间
     */
    public function getActiveRooms(): Collection
    {
        return $this->model->where('status', 'active')->get();
    }

    /**
     * 获取过期房间
     */
    public function getExpiredRooms(): Collection
    {
        return $this->model->where('status', 'expired')
            ->orWhere(function ($query) {
                $query->where('type', 'temporary')
                    ->where('expires_at', '<', now());
            })->get();
    }

    /**
     * 标记房间为过期
     */
    public function markAsExpired(int $roomId): bool
    {
        return $this->update($roomId, ['status' => 'expired']);
    }

    /**
     * 更新房间统计信息
     */
    public function updateStats(int $roomId, array $stats): bool
    {
        return $this->update($roomId, $stats);
    }

    /**
     * 更新最后活动时间
     */
    public function updateLastActivity(int $roomId): bool
    {
        return $this->update($roomId, ['last_activity_at' => now()]);
    }

    /**
     * 检查房间是否过期
     */
    public function isExpired(Room $room): bool
    {
        if ($room->type === 'permanent') {
            return false;
        }

        return $room->expires_at && $room->expires_at->isPast();
    }

    /**
     * 根据类型获取房间
     */
    public function getByType(string $type): Collection
    {
        return $this->model->where('type', $type)->get();
    }
}
